﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Geodatabase;

namespace EAGL.Core
{
    public class TObjectStreamSerializer
    {
        public byte[] Serialize(object o)
        {
            IObjectStream ostrm = new ObjectStreamClass();
            IXMLStream stream = new XMLStreamClass();
            ostrm.Stream = stream as IStream;
            ostrm.SaveObject(o);
            byte[] b = stream.SaveToBytes();
            return b;
        }

        public byte[] Serialize(object o, IServerContext context)
        {
            IObjectStream ostrm = context.CreateObject("esriSystem.ObjectStream") as IObjectStream;
            IXMLStream stream = context.CreateObject("esriSystem.XMLStream") as IXMLStream;
            ostrm.Stream = stream as IStream;
            ostrm.SaveObject(o);
            byte[] b = stream.SaveToBytes();
            return b;
        }

        public object Deserialize(byte[] bytes, Guid guid)
        {
            IObjectStream ostrm = new ObjectStreamClass();
            IXMLStream stream = new XMLStreamClass();
            ostrm.Stream = stream as IStream;
            stream.LoadFromBytes(ref bytes);
            object o = new object();
            o = ostrm.LoadObject(ref guid, null);
            return o;
        }

        public object Deserialize(byte[] bytes, IServerContext context, Guid guid)
        {
            IObjectStream ostrm = context.CreateObject("esriSystem.ObjectStream") as IObjectStream;
            IXMLStream stream = context.CreateObject("esriSystem.XMLStream") as IXMLStream;
            ostrm.Stream = stream as IStream;
            stream.LoadFromBytes(ref bytes);
            object o = ostrm.LoadObject(ref guid, null);
            return o;  
        }

        public void SaveToFile(object o, string fileName)
        {
            IObjectStream ostrm = new ObjectStreamClass();
            IXMLStream stream = new XMLStreamClass();
            ostrm.Stream = stream as IStream;
            ostrm.SaveObject(o);
            stream.SaveToFile(fileName);
        }

        public object LoadFromFile(string fileName, Guid guid)
        {
            IObjectStream ostrm = new ObjectStreamClass();
            IXMLStream stream = new XMLStreamClass();
            ostrm.Stream = stream as IStream;
            stream.LoadFromFile(fileName);
            object o = new object();
            o = ostrm.LoadObject(ref guid, null);
            return o; 
        }

    }
}
